<template>
  <div class="user-container">
    <!-- 左侧动态渐变背景 -->
    <div class="user-side">
      <div class="side-content">
        <h2>个人中心</h2>
        <p>管理您的账户信息与偏好设置</p>
      </div>
    </div>

    <!-- 右侧用户信息表单 -->
    <div class="user-form">
      <h3>账户信息</h3>

      <el-form :model="userInfo" label-position="top" class="form">
        <!-- 邮箱 -->
        <el-form-item label="邮箱地址">
          <el-input v-model="userInfo.email" :disabled="!!userInfo.email" placeholder="未绑定邮箱" />
          <el-button
            v-if="!userInfo.email"
            size="small"
            type="primary"
            @click="handleBindEmail"
            style="margin-top: 6px;"
          >
            绑定邮箱
          </el-button>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号码">
          <el-input v-model="userInfo.phone" :disabled="!!userInfo.phone" placeholder="暂不支持绑定手机" />
          <el-button
            v-if="!userInfo.phone"
            size="small"
            type="success"
            @click="handleBindPhone"
            style="margin-top: 6px;"
            disabled
          >
            绑定手机
          </el-button>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="登录密码">
          <el-input v-model="hiddenPassword" disabled placeholder="••••••••" />
          <div style="margin-top: 8px;">
            <el-button size="small" @click="openChangePasswordDialog">
              修改密码
            </el-button>
          </div>
        </el-form-item>

        <!-- VIP 状态 + 开通按钮 同行布局 -->
        <el-form-item label="会员状态">
          <div class="vip-container">
            <el-tag
              :type="userInfo.isVip ? 'success' : 'info'"
              size="large"
              class="vip-status"
            >
              {{ userInfo.isVip ? 'VIP 会员' : '普通用户' }}
            </el-tag>
            <el-button
              v-if="!userInfo.isVip"
              type="warning"
              size="large"
              class="vip-button"
              @click="handleOpenVip"
            >
              开通 VIP
            </el-button>
            <span v-else class="vip-disabled-text">已开通</span>
          </div>
        </el-form-item>

        <el-form-item label="免费次数"> 
          <el-tag>{{ userInfo.freeNum }}</el-tag>
        </el-form-item>
      </el-form>

      <div class="button-row">
        <el-button type="primary" class="feedback-btn" @click="showMyFeedback">
          我的反馈
        </el-button>
        <el-button type="warning" class="feedback-btn" @click="feedbackDialog">
          反馈
        </el-button>
        <el-button type="danger" plain class="feedback-btn" @click="handleLogout">
          退出登录
        </el-button>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <el-dialog v-model="showChangePassword" title="修改密码" width="400px" center>
      <!-- 切换验证方式 -->
      <el-radio-group v-model="updatePasswordType" class="method-toggle" style="margin-bottom: 15px;">
        <el-radio-button label="email">通过邮箱验证</el-radio-button>
        <el-radio-button label="phone" :disabled="!userInfo.phone">通过手机验证</el-radio-button>
      </el-radio-group>

      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
        <!-- 账号输入 -->
        <el-form-item prop="account">
          <el-input
            v-model="passwordForm.account"
            :placeholder="updatePasswordType === 'email' ? '请输入邮箱' : '请输入手机号'"
            :readonly="true"
            :value="updatePasswordType === 'email' ? userInfo.email : userInfo.phone"
          />
        </el-form-item>

        <!-- 验证码输入 -->
        <el-form-item prop="code">
          <el-input
            v-model="passwordForm.code"
            placeholder="请输入验证码"
            maxlength="6"
            clearable
          >
            <template #append>
              <el-button
                :disabled="countdown > 0 || !passwordForm.account"
                @click="sendVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <!-- 原密码 -->
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>

        <!-- 新密码 -->
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password minlength="6" maxlength="16" />
        </el-form-item>

        <!-- 确认新密码 -->
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showChangePassword = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword">确认修改</el-button>
      </template>
    </el-dialog>
  </div>

<!-- 反馈弹窗 -->
  <el-dialog 
    v-model="showFeedbackDialog" 
    :title="editingFeedbackId ? '修改问题' : '问题反馈'" 
    width="500px" 
    center
  >
  <el-form :model="feedbackForm" ref="feedbackFormRef">
    <el-form-item 
      label="问题描述" 
      prop="question" 
      :rules="[{ required: true, message: '请输入问题描述', trigger: 'blur' }]"
    >
      <el-input v-model="feedbackForm.question" type="textarea" rows="3" placeholder="请输入问题描述" />
    </el-form-item>

    <el-form-item label="图片上传(最多2张)">
      <el-upload
        class="upload-demo"
        action="#"
        list-type="picture-card"
        :limit="2"
        :before-upload="beforeUpload"
        :file-list="feedbackForm.files"
        :on-remove="handleRemoveFile"
        :http-request="uploadFileRequest"
        :on-exceed="handleExceed"
        multiple
      >
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>
  </el-form>

  <template #footer>
    <el-button @click="showFeedbackDialog = false">取消</el-button>
    <el-button type="primary" @click="submitFeedback">
      {{ editingFeedbackId ? '保存' : '反馈' }}
      </el-button>
    </template>
  </el-dialog>


  <!-- 我的反馈弹窗 -->
  <el-dialog v-model="showMyFeedbackDialog" title="我的反馈" width="800px" center>
    <el-table :data="myFeedbackList" style="width: 100%">
      <el-table-column type="index" label="序号" width="60"/>
      <el-table-column prop="question" label="问题描述"/>
      <el-table-column label="问题图片">
        <template #default="scope">
          <div style="display: flex; flex-wrap: wrap; gap: 6px;">
            <el-image
              v-for="(file, index) in scope.row.files"
              :key="index"
              style="width: 80px; height: 80px; object-fit: cover; cursor: pointer;"
              :src="file.url"
              :preview-src-list="scope.row.files.map(f => f.url)"
              :initial-index="index"
              fit="cover"
              preview-teleported
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间"/>
      <el-table-column label="解决时间">
        <template #default="scope">
          {{ scope.row.resolvedAt || '等待处理中' }}
        </template>
      </el-table-column>
      <el-table-column label="客服回复">
        <template #default="scope">
          {{ scope.row.result || '暂无' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="editFeedback(scope.row)"
            :disabled="scope.row.resolvedAt && scope.row.resolvedAt !== '等待处理中'"
          >
            修改
          </el-button>
          <el-button size="small" type="danger" @click="deleteFeedback(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {JmApi,decryptPassword}from '../api/jm.js'


import { getUserInfoApi, sendCodeApi, changePasswordApi,saveProblemApi, getProblemApi, updateProblemApi, deleteProblemApi,uploadFileApi, getPictureUrlApi  } from '../api/User'

// 用户信息
const userInfo = reactive({
  email: '',
  phone: '',
  isVip: false,
  freeNum: 0, 
})

// 反馈弹窗
const showFeedbackDialog = ref(false)
const showMyFeedbackDialog = ref(false)
const feedbackFormRef = ref(null)
const feedbackForm = reactive({ question: '', files: [], fileIds: [] })
// 修改密码弹窗
const showChangePassword = ref(false)
const passwordFormRef = ref(null)

const editingFeedbackId = ref(null)

// 修改密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  code: '',
  account: '' // 邮箱或手机号
})

// 上传前校验：只能是图片，且小于 5M
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB')
    return false
  }
  return true
}


// 删除已上传文件
const handleRemoveFile = (file) => {
  feedbackForm.files = feedbackForm.files.filter(f => f.id !== file.id)
  feedbackForm.fileIds = feedbackForm.fileIds.filter(id => id !== file.id)
}

// 上传文件
const uploadFileRequest = async ({ file, onSuccess, onError }) => {

  if (file.size / 1024 / 1024 >= 5) {
    ElMessage.error('上传图片大小不能超过 5MB')
    return onError(new Error('文件过大'))
  }

  try {
    const res = await uploadFileApi(file)
    if (res.code === 1) {
      feedbackForm.fileIds.push(res.data.id)
      feedbackForm.files.push({ name: file.name, url: res.data.url, id: res.data.id })
      onSuccess(res)
    } else {
      ElMessage.error(res.message)
      onError()
    }
  } catch (err) {
    ElMessage.error('上传失败')
    onError()
  }
}

// 验证方式：email 或 phone
const updatePasswordType = ref('email') // 默认邮箱

// 倒计时
const countdown = ref(0)

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const deleteFeedback = async (id) => {
  ElMessageBox.confirm('确定要删除这条反馈吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await deleteProblemApi(id) // 注意参数结构
    if (res.code === 1) {
      ElMessage.success('已删除')
      await loadMyFeedback()
    } else {
      ElMessage.error(res.message)
    }
  }).catch(() => {
    ElMessage.info('已取消')
  })
}


// 发送验证码
const sendVerificationCode = async () => {
  // 自动填充账号
  passwordForm.account = updatePasswordType.value === 'email' ? userInfo.email : userInfo.phone

  if (!passwordForm.account) {
    ElMessage.error('请先绑定邮箱或手机号')
    return
  }

  // 发送请求
  const params = {
  }

  if (updatePasswordType.value === 'email') {
    params.email = passwordForm.account
    params.loginType = "emailcode"
  } else {
    params.loginType = "phonecode"
    params.phone = passwordForm.account
  }

  const result = await sendCodeApi(params)
  if (result.code === 1) {
    ElMessage.success('验证码已发送')
    startCountdown()
  } else {
    ElMessage.error(result.message)
  }
}

// 获取用户信息
const getUserInfo = async () => {
  const result = await getUserInfoApi()
  if (result.code === 1) {
    localStorage.setItem('userId', result.data.id)
    userInfo.email = result.data.email
    userInfo.phone = result.data.phone
    userInfo.isVip = result.data.isVip || false
    userInfo.freeNum = result.data.freeNum || 0
  } else {
    ElMessage.error(result.message)
  }
}

onMounted(() => {
  getUserInfo()
})

// 密码规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 隐藏密码显示
const hiddenPassword = computed(() => '••••••••')

// 打开修改密码弹窗
const openChangePasswordDialog = () => {
  // 自动填充当前绑定的账号
  passwordForm.account = updatePasswordType.value === 'email' ? userInfo.email : userInfo.phone
  showChangePassword.value = true
}

// 处理修改密码
const handleChangePassword = async () => {
  passwordFormRef.value?.validate(async (valid) => {
    if(passwordForm.code === ''){
      ElMessage.error('请输入验证码');
      return;
    }

    if(passwordForm.code.length !== 6){
      ElMessage.error('验证码长度不合规');
      return;
    }
    
    if (valid) {
      const params = {
        ...passwordForm,
      }
      params.password = passwordForm.newPassword
      // 加密
      params.password = JmApi(params.password)
      params.newPassword = JmApi(params.newPassword)
      params.confirmPassword = JmApi(params.confirmPassword)
      params.oldPassword = JmApi(params.oldPassword)

      if (updatePasswordType.value === 'email') {
        params.email = passwordForm.account
        params.loginType = "emailcode"
      } else {
        params.loginType = "phonecode"
        params.phone = passwordForm.account
      }
      const result = await changePasswordApi(params)
      if (result.code !== 1) {
        params.password = decryptPassword(params.password)
        params.newPassword = decryptPassword(params.newPassword)
        params.confirmPassword = decryptPassword(params.confirmPassword)
        params.oldPassword = decryptPassword(params.oldPassword)
        if(result.message === 'CodeExpired')
        ElMessage.error("验证码已经过期");
        else if(result.message === 'CodeError')
        ElMessage.error("验证码错误");
        else if(result.message === 'OldPasswordError')
        ElMessage.error("旧密码错误");
        else ElMessage.error(result.message);
        return
      }
      ElMessage.success('密码修改成功！')
      showChangePassword.value = false
      // 重置表单
      Object.assign(passwordForm, {
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
        code: ''
      })
    } else {
      ElMessage.error('请检查输入内容')
    }
  })
}

// 绑定邮箱
const handleBindEmail = () => {
  ElMessageBox.prompt('请输入您的邮箱地址', '绑定邮箱', {
    inputType: 'email',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValidator: (value) => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      return emailRegex.test(value) ? null : '请输入有效的邮箱地址'
    }
  }).then(({ value }) => {
    userInfo.email = value
    ElMessage.success('邮箱绑定成功！')
  }).catch(() => {
    ElMessage.info('已取消绑定')
  })
}

// 绑定手机
const handleBindPhone = () => {
  ElMessageBox.prompt('请输入您的手机号码', '绑定手机', {
    inputType: 'tel',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValidator: (value) => {
      const phoneRegex = /^1[3-9]\d{9}$/
      return phoneRegex.test(value) ? null : '请输入有效的手机号'
    }
  }).then(({ value }) => {
    userInfo.phone = value
    ElMessage.success('手机绑定成功！')
  }).catch(() => {
    ElMessage.info('已取消绑定')
  })
}

// 开通 VIP
const handleOpenVip = () => {
  ElMessageBox.confirm('开通 VIP 会员可享受更多特权，是否立即开通？', '开通 VIP', {
    confirmButtonText: '立即开通',
    cancelButtonText: '再想想',
    type: 'warning'
  }).then(() => {
    userInfo.isVip = true
    ElMessage.success('VIP 开通成功！')
  }).catch(() => {
    ElMessage.info('已取消开通')
  })
}

// 退出登录
const router = useRouter()
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '退出登录', {
    confirmButtonText: '退出',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    localStorage.removeItem('token')
    localStorage.removeItem('userId')
    ElMessage.success('已退出登录')
    router.push('/login')
  }).catch(() => {
    ElMessage.info('已取消')
  })
}

// 我的反馈列表
const myFeedbackList = ref([
  // 示例数据
  {
    question: '示例问题1',
    files: [],
    createdAt: '2025-09-17 16:00',
    resolvedAt: null
  }
])

// 超出数量限制
const handleExceed = () => {
  ElMessage.warning('最多只能上传 2 张图片')
}

// 提交反馈
const submitFeedback = async () => {
  if (!feedbackForm.question) {
    ElMessage.error('请输入问题描述')
    return
  }

  const params = {
    question: feedbackForm.question,
    picture: feedbackForm.fileIds.join(','),
    userId: localStorage.getItem('userId'),
    id: editingFeedbackId.value || null
  }

  let res
  if (editingFeedbackId.value) {
    // 修改
    res = await updateProblemApi(params)
  } else {
    // 新增
    res = await saveProblemApi(params)
  }

  if (res.code === 1) {
    ElMessage.success(editingFeedbackId.value ? '反馈已更新' : '反馈已提交')
    showFeedbackDialog.value = false
    // 重置
    feedbackForm.question = ''
    feedbackForm.files = []
    feedbackForm.fileIds = []
    editingFeedbackId.value = null
    loadMyFeedback()
  } else {
    ElMessage.error(res.message)
  }
}



// 编辑反馈
const editFeedback = (row) => {
  editingFeedbackId.value = row.id
  feedbackForm.question = row.question
  feedbackForm.files = [...row.files]
  feedbackForm.fileIds = row.files.map(f => f.id)
  showFeedbackDialog.value = true
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  const hh = String(date.getHours()).padStart(2, '0')
  const mm = String(date.getMinutes()).padStart(2, '0')
  const ss = String(date.getSeconds()).padStart(2, '0')
  return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}


// 查询我的反馈
const loadMyFeedback = async () => {
  const res = await getProblemApi()
  if (res.code === 1) {
    const list = res.data || []
    // 处理数据
    for (const item of list) {
      // 映射时间字段
      item.createdAt = formatTime(item.createTime)
      item.resolvedAt = item.endTime ? formatTime(item.endTime) : null

      // 处理图片 ids → url
      if (item.picture) {
        const ids = item.picture.split(',').map(i => parseInt(i))
        const picRes = await getPictureUrlApi(ids)
        if (picRes.code === 1) {
          item.files = picRes.data.map(p => ({ url: p.url, id: p.id }))
        }
      } else {
        item.files = []
      }
    }
    myFeedbackList.value = list
  }
}
// 打开我的反馈
const showMyFeedback = async () => {
  showMyFeedbackDialog.value = true
  await loadMyFeedback()
}

const feedbackDialog = async () => {
  // 重置
  editingFeedbackId.value = null
  feedbackForm.question = ''
  feedbackForm.files = []
  feedbackForm.fileIds = []
  showFeedbackDialog.value = true
}

</script>

<style scoped>
.button-row {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.feedback-btn {
  flex: 1;
}


.user-container {
  display: flex;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 左侧动态渐变背景 */
.user-side {
  flex: 1;
  background: linear-gradient(45deg, #12005e, #667eea, #4ade80, #fbbf24, #ec4899);
  background-size: 400% 300%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  animation: gradientShift 20s ease infinite;
}

@keyframes gradientShift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.side-content h2 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.side-content p {
  font-size: 1.2rem;
  opacity: 0.95;
}

/* 右侧表单区域 */
.user-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 3rem;
  background-color: #f8f9fa;
  max-width: 600px;
  margin: 0 auto;
}

.user-form h3 {
  margin-bottom: 2rem;
  color: #333;
  font-weight: 600;
  text-align: center;
}

.form {
  max-width: 400px;
  margin: 0 auto;
}

/* VIP 状态与按钮布局 */
.vip-container {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.vip-status {
  flex: 1;
  min-width: 180px;
  text-align: center;
}

.vip-button {
  flex: 1;
  min-width: 180px;
  font-weight: 600;
}

.vip-disabled-text {
  color: #67c23a;
  font-size: 14px;
  margin-left: 10px;
}

/* 响应式 */
@media (max-width: 768px) {
  .user-container {
    flex-direction: column;
  }
  .user-side {
    padding: 1.5rem;
  }
  .user-side h2 {
    font-size: 2rem;
  }
  .user-form {
    padding: 2rem 1.5rem;
  }
  .vip-container {
    flex-direction: column;
    align-items: stretch;
  }
  .vip-button, .vip-status {
    min-width: auto;
  }
}
</style>